#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <fcntl.h>  // For fcntl
#include <time.h>   // For time()
#include <unistd.h> // For close()
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/ioctl.h> // For ioctl (alternative method)
#include <string.h>    // For memset

#define SERVER_PORT 8888 // Port to attempt connection (likely no server running for timeout test)

int main(int argc, char **argv)
{ // Changed return type to int
    int sock;
    struct sockaddr_in server_addr; // Renamed for clarity
    int nonblock_flag = 1;          // 1 for non-blocking, 0 for blocking
    time_t t1, t2;

    if (argc < 3)
    {
        printf("Usage: %s <server_ip> <0|1> (0 for blocking, 1 for non-blocking)\n", argv[0]);
        exit(1);
    }

    nonblock_flag = atoi(argv[2]); // Get blocking/non-blocking choice

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("socket create error!");
        exit(1);
    }

    if (nonblock_flag == 1)
    {
        printf("Setting NON-BLOCKING mode...\n");
        int flags = fcntl(sock, F_GETFL, 0);
        if (flags < 0)
        {
            perror("fcntl F_GETFL error");
            close(sock);
            exit(1);
        }
        if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0)
        {
            perror("fcntl F_SETFL O_NONBLOCK error");
            close(sock);
            exit(1);
        }
    }
    else
    {
        printf("Using BLOCKING mode...\n");
    }

    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(SERVER_PORT); // Use a defined port

    if (inet_aton(argv[1], &server_addr.sin_addr) == 0)
    {
        fprintf(stderr, "Invalid server IP address: %s\n", argv[1]);
        close(sock);
        exit(1);
    }

    printf("Attempting to connect to %s:%d...\n", argv[1], SERVER_PORT);
    t1 = time(NULL);
    int connect_ret = connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in)); // Use sizeof(struct sockaddr_in)
    t2 = time(NULL);

    if (connect_ret < 0)
    {
        if (nonblock_flag == 1 && errno == EINPROGRESS)
        {
            printf("connect() returned -1 with errno EINPROGRESS (non-blocking mode).\n");
        }
        else
        {
            perror("connect error");
        }
    }
    else
    {
        printf("connect() succeeded immediately.\n");
    }

    printf("connect call took approximately %d seconds.\n", (int)(t2 - t1));

    close(sock);
    return 0; // Added return
}